package javango.forms.fields;

import java.util.Locale;
import java.util.Map;

import javango.forms.widgets.CheckboxWidget;
import javango.forms.widgets.WidgetFactory;

import org.apache.commons.lang.StringUtils;

import com.google.inject.Inject;

public class BooleanField extends AbstractField {

	/**
	 * Returns true if value exaluates to a true value or false if it evaluates to a false value,  or NULL if it is not either.
	 * @param value
	 */
	public static Boolean checkBooleanValue(Object value) {
		if (value == null) return null;
		
		String tmpStr = value.toString().toLowerCase(Locale.getDefault());    	
        if ("false".equals(tmpStr) || "f".equals(tmpStr) || "no".equals(tmpStr) || "n".equals(tmpStr) || "off".equals(tmpStr)) {
        	return false;
        }
        if ("true".equals(tmpStr) || "t".equals(tmpStr) || "yes".equals(tmpStr) || "y".equals(tmpStr) || "on".equals(tmpStr)) {
        	return true;
        }
        return null;
	}
	
	@Inject
	public BooleanField(WidgetFactory widgetFactory) {
		super(widgetFactory);
		setWidget(CheckboxWidget.class);
	}

	public Object clean(String value, Map<String, String> errors) {
		if (StringUtils.isEmpty(value)) {
			if (this.isRequired()) {
				errors.put(getName(), "Required");
				return null;
			} else {
				return null;
			}
		}
		
        Boolean myValue = checkBooleanValue(value);
        if (myValue != null) return myValue;
        
        errors.put(getName(), String.format("Unknown value '%s'", value));
        return null;
	}
}
